package li.webqq.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

/**
 * @author 明伟
 */
public class ReflectUtil {
    public static <T> T born(Class<T> type) {
        try {
            return type.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Field getField(Class<?> type, String name) {
        try {
            return type.getDeclaredField(name);
        } catch (Exception e) {
            return null;
        }
    }

    public static boolean isDateTimeLike(Class<?> klass) {
        return Calendar.class.isAssignableFrom(klass) || java.util.Date.class.isAssignableFrom(klass) || java.sql.Date.class.isAssignableFrom(klass) || java.sql.Time.class.isAssignableFrom(klass);
    }

    public static boolean isBoolean(Class<?> klass) {
        return is(klass, boolean.class) || is(klass, Boolean.class);
    }

    public static boolean isNumber(Class<?> klass) {
        return Number.class.isAssignableFrom(klass) || klass.isPrimitive() && !is(klass, boolean.class) && !is(klass, char.class);
    }

    public static boolean is(Class<?> type, Class<?> klass) {
        return null != type && klass == type;
    }

    public static void set(Object target, Field field, Object value) {
        try {
            field.setAccessible(true);
            field.set(target, value + "");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Object get(Object target, Field field) {
        try {
            field.setAccessible(true);
            return field.get(target);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static List<Field> getFields(Class<?> type) {
        List<Field> fields = new ArrayList<Field>();
        Collections.addAll(fields, type.getDeclaredFields());
        if (Object.class != type.getSuperclass()) {// 扫描超类的Field
            fields.addAll(getFields(type.getSuperclass()));
        }
        return fields;
    }
}